﻿using ExcelUnity.Exporter.Exporters;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace ExcelUnity.Exporter.Wrappers.SheetWrapperBuilders
{
    public class DataTableBuilder : BaseBuilder
    {
        public override List<ColumnAdapter> BuildColumnAdapter(ExportSheet sheet)
        {
            var colIndex = 0;
            var columns = new Dictionary<int, string>();
            foreach (DataColumn col in sheet.Table!.Columns)
                columns.Add(colIndex++, col.ToString());

            var columnAdapters = sheet.ToAdapters(columns);
            return columnAdapters;
        }

        public override IEnumerable<ExportRowWrapper> FillDataRows(ExportSheet sheet, List<ColumnAdapter> columnAdapters, int rowIndex)
        {
            var colAdapterDic = columnAdapters.ToDictionary(x => x.ColumnIndex);
            //填充行
            for (int i = 0; i < sheet.Table!.Rows.Count; i++)
            {
                var cells = new List<ExportCellWrapper>();
                for (int j = 0; j < sheet.Table!.Columns.Count; j++)
                {
                    var adapter = colAdapterDic[j];

                    var val = sheet.Table!.Rows[i][j].ToString();
                    var cell = new ExportCellWrapper(val, adapter);
                    if (adapter.SpecialCellStyle?.ContainsKey(val) ?? false)
                        cell.CellStyle = adapter.SpecialCellStyle[val];

                    cells.Add(cell);
                }

                yield return new ExportRowWrapper(cells, rowIndex++);
            }
        }
    }
}
